class Solution
{
public:
    int minimumDifference(vector<int> &nums, int k)
    {
        int n = nums.size();
        vector<vector<int>> nextZero(n, vector<int>(32, n));
        for (int i = n - 2; i >= 0; --i)
        {
            for (int j = 0; j <= 31; ++j)
            {
                if (!(nums[i + 1] & (1 << j)))
                {
                    nextZero[i][j] = i + 1;
                }
                else
                {
                    nextZero[i][j] = nextZero[i + 1][j];
                }
            }
        }

        int result = INT_MAX;
        for (int i = 0; i < n; ++i)
        {
            int cur = nums[i];
            int p = i;
            result = min(result, abs(k - cur));
            while (true)
            {
                int next = n;
                for (int j = 0; j <= 31; ++j)
                {
                    if (cur & (1 << j))
                    {
                        next = min(next, nextZero[p][j]);
                    }
                }
                if (next == n)
                {
                    break;
                }
                cur = cur & nums[next];
                result = min(result, abs(k - cur));
                p = next;
            }
        }
        return result;
    }
};